# -*- coding: utf-8 -*-
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
from sklearn import preprocessing
from nets import FCNetA, FCNetB, FCNetC, FCNetD, FCNetE, FCNetF, FCNetG
from keras.optimizers import SGD
from keras.optimizers import Adam
import numpy as np

BATCH_SIZE = 64
EPOCHS = 300
DIM = 27

args = {"model": "./fc.model", "output": "./result.png"}

dataset = np.loadtxt('./data.csv', delimiter=',')

X = dataset[:24000, 1:]
Y = dataset[:24000, 0]

# 通过对数据循环右移，在交叉验证中使用不同的划分
shift = 4000 * 5
X = np.vstack([X[-shift:], X[:-shift]])
Y = np.concatenate([Y[-shift:], Y[:-shift]])

# 归一化
scaler = preprocessing.MinMaxScaler()
X = scaler.fit_transform(X)

# 划分训练集和验证集
trainX = X[:20000, :]
testX = X[20000:, :]
trainY = Y[:20000]
testY= Y[20000:]
 
print("[INFO] compiling model...")
#opt = SGD(lr=0.01, momentum=0.9, nesterov=True)
opt = Adam(lr=0.001, beta_1=0.9, beta_2=0.999, epsilon=None, decay=0.0, amsgrad=False)
model = FCNetA.build(DIM)
model.compile(loss="binary_crossentropy", optimizer=opt, metrics=['accuracy'])
print(model.summary())
print("[INFO] training network...")
H = model.fit(trainX, trainY, validation_data=(testX, testY), batch_size=BATCH_SIZE, 
	epochs=EPOCHS)

# 查找最小损失和最大精度
i = 0
min_loss = 10
min_loss_epoch = 0
for item in H.history["val_loss"]:
	i += 1
	if item < min_loss:
		min_loss = item
		min_loss_epoch = i
i = 0
max_acc = 0
max_acc_epoch = 0
for  item in H.history["val_acc"]:
	i += 1
	if item > max_acc:
		max_acc = item
		max_acc_epoch = i

print("\nmin val_loss: %f (at epoch %d)" % (min_loss, min_loss_epoch))
print("max val_acc: %f (at epoch %d)" % (max_acc, max_acc_epoch))

# 保存模型
model.save(args["model"])

# 画图
plt.style.use("ggplot")
plt.figure()
plt.plot(np.arange(0, EPOCHS), H.history["loss"], label="train_loss")
plt.plot(np.arange(0, EPOCHS), H.history["val_loss"], label="val_loss")
plt.plot(np.arange(0, EPOCHS), H.history["acc"], label="train_acc")
plt.plot(np.arange(0, EPOCHS), H.history["val_acc"], label="val_acc")
plt.title("Training Loss and Accuracy")
plt.xlabel("# Epoch")
plt.ylabel("Loss/Accuracy")
plt.legend()
plt.savefig(args["output"])
